<!-- tabs -->
<template>
	<view class="tabs-placeholder">
		<cover-view class="tabs">
			<cover-view class="tabs-item" v-for="(item, index) in tabs" :key="item.value"
				:class="[{'active': item.value === tabsValue}, 'tabs-item-' + index]"
				@click="handleChangeTab(item, index)">
				{{item.label}}
			</cover-view>
			<cover-view class="swiper" :style="{'transform': `translate(${swiperLeft}, 0)`}"></cover-view>
		</cover-view>
	</view>
</template>

<script setup>
	import { ref, onMounted, getCurrentInstance, nextTick, computed } from 'vue';

	const emits = defineEmits(['update:modelValue', 'change']);
	const tabsValue = defineModel();
	const tabs = [
		{ value: '0', label: '近7天' },
		{ value: '1', label: '本月' },
		{ value: '2', label: '自定义' },
	];

	// 导航栏高度
	const navbarHeight = function() {
		const statusBarHeight = getApp().globalData.statusBarHeight;
		const navBarHeight = getApp().globalData.navBarHeight;
		return statusBarHeight + navBarHeight + 'px';
	}();

	// 获取页面实例对象
	let query = null;
	let swiperHalfWidth = 0;
	onMounted(() => {
		query = uni.createSelectorQuery().in(getCurrentInstance());

		query.select('.swiper').boundingClientRect((data) => {
			swiperHalfWidth = data.width / 2;
		}).exec();

		handleChangeTab(tabs[tabsValue.value], tabsValue.value);
	});

	const swiperLeft = ref('');
	const handleChangeTab = (item, index) => {
		// if (tabsValue.value === item.value) return;
		emits('change', item.value);
		emits('update:modelValue', item.value);

		nextTick(() => {
			query.select('.tabs-item-' + index).boundingClientRect((data) => {
				swiperLeft.value = data.left + data.width / 2 - swiperHalfWidth + 'px';
			}).exec();
		})
	}
</script>

<style lang="scss" scoped>
	.tabs-placeholder {
		height: 86rpx;
	}

	.tabs {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 9;
		width: 100%;
		display: flex;
		justify-content: space-evenly;
		align-items: flex-end;
		height: 86rpx;
		padding-bottom: 18rpx;
		background-color: white;
		box-sizing: border-box;

		&-item {
			flex-shrink: 0;
			font-weight: 500;
			font-size: 30rpx;
			color: #666666;
			line-height: 1;
			padding: 20rpx 30rpx 0;
			min-width: 100rpx;
			text-align: center;
			transition: font-size 0.2s;

			&.active {
				font-weight: bold;
				font-size: 34rpx;
				color: #222222;
			}
		}

		.swiper {
			position: absolute;
			bottom: 0;
			left: 0;
			width: 46rpx;
			height: 9rpx;
			background: #FE3C26;
			border-radius: 5rpx;
			// transform: translateX(-50%);
			transition: left 0.2s;
		}
	}
</style>